document.addEventListener("DOMContentLoaded", function() {
    let registrationForm = document.querySelector("form[action='']");

    registrationForm.addEventListener("submit", function(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        let username = document.querySelector("input[type='text']").value;
        let password = document.querySelector("input[type='password']").value;
        let email = document.querySelector("input[type='email']").value;

        if (username.trim() !== "" && password.trim() !== "" && email.trim() !== "") {
            // 用户名、密码和邮箱均不为空时，进行页面跳转
            let xhr = new XMLHttpRequest();

            // 设置POST请求，将数据发送到指定的URL
            xhr.open("POST", "/register_action", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            // 设置回调函数，处理服务器响应
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // 服务器返回的数据
                    let response = xhr.responseText;
                    // 在这里根据服务器返回的数据进行判断，然后跳转或弹出提示
                    if (response === "success") {
                        console.log(response);
                        window.location.href = "/login_page";
                    } else if(response === "Account exists")
                    {
                        alert("用户名已存在");
                    }

                    else {
                        alert("登录失败，请检查用户名和密码。");
                    }
                }
            };
            let formData = new URLSearchParams();
            formData.append("username", username);
            formData.append("password", password);
            formData.append("email", email);


            xhr.send(formData);
        } else {
            // 任一信息为空时，可以添加相应的提示逻辑
            alert("请输入完整的用户名、密码和邮箱信息");
        }
    });

});
